package com.electric.electric.Common.Config;


import com.electric.electric.serviceimpl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {

    @Autowired
    private UserDetailsServiceImpl userDetailsService; // 注入你的实现

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable()) //禁用CSRF 适用于 Token 认证的前后端分离项目。
                //  禁用默认登录页和 Basic 认证
                //  配置 CORS
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                //  设置 Session 为无状态（不使用 Cookie，适用于 Token 认证）
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .formLogin(form -> form.disable())
                .httpBasic(basic -> basic.disable())
                .exceptionHandling(ex -> {
                    ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); // 未认证处理
                    ex.accessDeniedHandler((req, res, ex2) -> res.setStatus(HttpStatus.FORBIDDEN.value())); // 未授权处理
                });;



        return http.build();

    }

    // CORS 配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // 允许携带凭证（如 Cookie）
        config.addAllowedOriginPattern("http://8.137.13.44:8070"); // 前端地址（生产环境替换为实际域名）
        config.addAllowedOriginPattern("http://localhost:5173"); // 前端地址（生产环境替换为实际域名）
        config.addAllowedMethod("*"); // 允许所有方法
        config.addAllowedHeader("*"); // 允许所有头
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    // 关键：覆盖默认的 UserDetailsService，禁用默认用户生成
    @Bean
    public UserDetailsService userDetailsService() {
        // 返回空的 UserDetailsService，阻止默认用户生成
        return userDetailsService;
    }

    // 密码编码器（即使使用 Token 认证，也需定义此 Bean）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10); // 安全加密
    }


}
